//
//  NetworkingViewManager.m
//  ZYOnlineSchool
//
//  Created by 毕武侠 on 2017/3/3.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "NetworkingViewManager.h"

@interface NetworkingViewManager ()

@property (nonatomic, strong) BaseViewModel *viewModel;
@property (nonatomic, strong, readwrite) NSString *msg;

@end

@implementation NetworkingViewManager

- (void)setupConfigure {
    self.viewModel = [[BaseViewModel alloc] initWithUrl:self.url];
    self.receiveSignal = self.viewModel.command.executionSignals.switchToLatest;
    self.errorSignal = self.viewModel.command.errors;
}

#pragma mark - getter 

- (NSString *)msg {
    return self.viewModel.msg;
}

#pragma mark - setter

- (void)setUrl:(NSString *)url {
    _url = url;
    self.viewModel.url = url;
}

- (void)setSendSignal:(RACSignal *)sendSignal {
    _sendSignal = sendSignal;
    
    [_sendSignal subscribeNext:^(id x) {
        self.viewModel.params.body = x;
        [self.viewModel.command execute:self.rmodel ? : @"BaseModel"];
    }];
}

// 方式二
- (void)loadDataWithParams:(NSDictionary *)params {
    self.viewModel.params.body = params;
    [self.viewModel.command execute:self.rmodel];
}

// 请求时，增加转圈
- (void)setupLoadingView:(UIView *)view {
    [self.viewModel.command.executionSignals.switchToLatest subscribeNext:^(NSMutableArray *receive) {
        [MBProgressHUD hideHUDForView:view animated:YES];
    }];
    
    [self.viewModel.command.executing subscribeNext:^(NSNumber *executing) {
        if (executing.boolValue) {      // 正在加载
            [MBProgressHUD showLoadingImageToView:view];
        }
    }];
    
    [self.viewModel.command.errors subscribeNext:^(NSError *error) {
        [MBProgressHUD hideHUDForView:view animated:NO];
        if (![SettingObject objectIsValid:self.viewModel.msg]) {
            self.viewModel.msg = error.domain;
        }
        [MBProgressHUD showTextOnly:view message:self.viewModel.msg];
    }];
}

@end
